/**
*  \file interpol_u16_s32.c
*
*  \brief
*
*  \author Michael J. Hohmann  <michael.hohmann@linde-mh.de>
*
*
*/

/*===============================================[ private includes  ]================================================*/
#include "interpol_u16_s32.h"
#include "../assertor/assertor.h"
#include "../pal/pal_mem.h"
#include "../mlib/absdiff.h"

/*===============================================[ private defines   ]================================================*/

/*===============================================[ private datatypes ]================================================*/

/*===============================================[ private variables ]================================================*/

/*===============================================[ private functions ]================================================*/

/*================================================[ inline functions ]================================================*/

/*================================================[ public functions ]================================================*/

S32 interpol_u16_s32(struct interpol_u16_s32_obj const* me, U16 value)
{
   ASSERTOR_PRE(NIL != me, "NULL is not allowed as object pointer.");
   {
      pal_size_t min = 0;
      pal_size_t max = me->count - 1;

      /* perform a binary search over table elements. */
      while ((max - min) > 1)
      {
         pal_size_t cursor = min + (max - min) / 2;
         if (me->x[cursor] > value)
         {
            max = cursor;
         }
         else
         {
            min = cursor;
         }
      }

      /* calculate interpolation of two immediate neighbor nodes */
      {
         S32 xval = value;

         S32 x1 = me->x[min];
         S32 y1 = me->y[min];

         S32 x2 = me->x[max];
         S32 y2 = me->y[max];

         S32 rv;


         if ( absdiff_s32(y2,  y1) <= U32_CONST(1<<16) )
         {
            rv = ( ( (y2 - y1) * (xval-x1) ) / (x2 - x1)) + y1;
         }
         else
         {
            S32 slope = (y2 - y1) / (x2 - x1);
            rv = slope* (xval-x1) +y1;
         }


         return  rv;
      }
   }
}

/*===============================================[ private functions ]================================================*/


/***********************************************************************************************************************
*                             Copyright 2018 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/
